<template>
  <div class="login-container" :style="{ '--login-gap': loginGap + 'px' }">
    <!-- 左侧信息区域 -->
    <div class="left-section" :style="{ marginLeft: leftOffset + 'px' }">
      <div class="logo-section">
        <h1 class="app-title">iMES</h1>
        <span class="badge">工厂管家</span>
      </div>
       
      
      <div class="features-list">
        <div class="feature-item">最值得信赖的新一代工厂管家</div>
        <div class="feature-item">计划管理,工单,订单,生产管理,库存管理</div>
        <div class="feature-item">工序,报工,基础数据,大屏,报表</div>
        <div class="feature-item">手机APP移动端管理,无需电脑</div>
        <div class="feature-item">演示账号: admin 密码:123456</div>
      </div>
      
      <div class="action-buttons" :style="{ marginTop: actionsOffset + 'px' }">
        <el-button class="action-btn">亮点说明</el-button>
        <el-button class="action-btn">项目介绍</el-button>
        <el-button class="action-btn">视频介绍</el-button>
        <el-button class="action-btn">补充介绍</el-button>
        <el-button class="action-btn primary">Java版本</el-button>
      </div>
    </div>

    <!-- 右侧登录表单 -->
    <div class="right-section">
      <div class="login-card">
        <div class="commercial-badge">商业版</div>
        
        <h2 class="login-title">账号登录</h2>
        
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules" 
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="输入用户"
              size="large"
              prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="captcha">
            <div class="captcha-container">
              <el-input
                v-model="loginForm.captcha"
                placeholder="输入验证码"
                size="large"
                class="captcha-input"
              />
              <div class="captcha-image" @click="refreshCaptcha">
                <canvas ref="captchaCanvas" width="100" height="40"></canvas>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              size="large" 
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="download-links">
          <a href="#" class="download-link">桌面客户端</a>
          <a href="#" class="download-link">
            <el-icon><Iphone /></el-icon>
            小程序
          </a>
          <a href="#" class="download-link">
            <el-icon><Platform /></el-icon>
            Android
          </a>
          <a href="#" class="download-link">
            <el-icon><Monitor /></el-icon>
            H5
          </a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, Iphone, Monitor, Platform } from '@element-plus/icons-vue'

import { useRouter } from 'vue-router'
import { MES_XHY_ApiHost } from '@/utils/Interceptors'


const router = useRouter()
const loginFormRef = ref()
const captchaCanvas = ref<HTMLCanvasElement>()
const loading = ref(false)

// 左侧文字与右侧登录模块的水平间距（像素），可按需调整
const loginGap = ref(36)

// 按钮模块与上方文字的垂直间距（像素），可按需调整
const actionsOffset = ref(28)

// 左侧文字模块的水平偏移量（像素），正值向右移动，负值向左移动
const leftOffset = ref(36)

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

// 验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 生成验证码
const generateCaptcha = () => {
  if (!captchaCanvas.value) return
  
  const canvas = captchaCanvas.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 设置背景色
  ctx.fillStyle = '#f0f0f0'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 生成随机验证码
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let captcha = ''
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  
  // 绘制验证码文字
  ctx.font = 'bold 20px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  
  for (let i = 0; i < captcha.length; i++) {
    const x = 20 + i * 20
    const y = 20
    const rotation = (Math.random() - 0.5) * 0.3
    
    ctx.save()
    ctx.translate(x, y)
    ctx.rotate(rotation)
    ctx.fillStyle = `hsl(${Math.random() * 360}, 70%, 50%)`
    ctx.fillText(captcha[i], 0, 0)
    ctx.restore()
  }
  
  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `hsl(${Math.random() * 360}, 70%, 70%)`
    ctx.lineWidth = 1
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }
  
  // 添加干扰点
  for (let i = 0; i < 20; i++) {
    ctx.fillStyle = `hsl(${Math.random() * 360}, 70%, 70%)`
    ctx.fillRect(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      1,
      1
    )
  }
  
  // 存储验证码用于验证
  localStorage.setItem('captcha', captcha)
}

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha()
}

// 验证验证码
const validateCaptcha = (input: string) => {
  const storedCaptcha = localStorage.getItem('captcha')
  return storedCaptcha && storedCaptcha.toLowerCase() === input.toLowerCase()
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    
    // 验证验证码
    if (!validateCaptcha(loginForm.captcha)) {
      ElMessage.error('验证码错误')
      refreshCaptcha()
      return
    }
    
    loading.value = true
    
    const response = await MES_XHY_ApiHost.post('/api/Login/login', {
      account: loginForm.username,
      password: loginForm.password
    })
    
    if (response.data.code === 200) {
      ElMessage.success('登录成功')
      
      // 保存用户信息和token
      localStorage.setItem('userInfo', JSON.stringify(response.data.data))
      localStorage.setItem('token', response.data.data.token || '')
      
      // 跳转到首页
      router.push('/home')
    } else {
      ElMessage.error(response.data.msg || '登录失败')
    }
  } catch (error: any) {
    console.error('登录错误:', error)
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('登录失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 设置页面标题
const setPageTitle = () => {
  document.title = 'iMES-您的新一代工厂管家【商业版】'
}

// 组件挂载后生成验证码
onMounted(() => {
  // 设置页面标题
  setPageTitle()
  
  nextTick(() => {
    generateCaptcha()
  })
  
  // 监听页面可见性变化
  const handleVisibilityChange = () => {
    if (!document.hidden) {
      setPageTitle()
    }
  }
  
  document.addEventListener('visibilitychange', handleVisibilityChange)
  
  // 清理事件监听器
  onUnmounted(() => {
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  })
})
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  margin: 0;
  padding: 0;
  justify-content: center;      /* 居中整体内容 */
  align-items: center;           /* 垂直居中 */
  column-gap: var(--login-gap, 36px); /* 自定义左右间距 */
}

.left-section {
  flex: 1;
  padding: 60px 40px;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow: hidden;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 40px;
}

.app-title {
  font-size: 48px;
  font-weight: bold;
  margin: 0;
}

.badge {
  background: #4caf50;
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.features-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
}

.feature-item {
  display: flex;
  align-items: center;
  font-size: 16px;
  line-height: 1.6;
}

.feature-item::before {
  content: '';
  width: 8px;
  height: 8px;
  background: white;
  border-radius: 50%;
  margin-right: 15px;
  flex-shrink: 0;
}

.action-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  margin-top: 28px; /* 兜底默认间距，支持脚本覆盖 */
}

.action-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
}

.action-btn.primary {
  background: #4caf50;
  border-color: #4caf50;
}

.action-btn.primary:hover {
  background: #45a049;
  border-color: #45a049;
}

.right-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  overflow: hidden;
}

.login-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.commercial-badge {
  position: absolute;
  top: 0;
  right: 0;
  background: #2196f3;
  color: white;
  padding: 8px 16px;
  font-size: 12px;
  transform: rotate(45deg) translate(30px, -10px);
  transform-origin: center;
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #333;
}

.login-form {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  gap: 15px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.captcha-image:hover {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
}

.download-links {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.download-link {
  color: #666;
  text-decoration: none;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.3s ease;
}

.download-link:hover {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
  
  .left-section {
    padding: 30px 20px;
    text-align: center;
  }
  
  .app-title {
    font-size: 36px;
  }
  
  .features-list {
    margin: 30px 0;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .right-section {
    padding: 20px;
  }
  
  .login-card {
    padding: 30px 20px;
  }
}

/* 防止页面晃动 */
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

html {
  overflow: hidden;
}
</style>